package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/pkg/errors"
	"os"
	"time"
)

var DB *sql.DB

func getNames() ([]string, error) {
	rows, err := DB.Query("SELECT name FROM user")

	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			// 我觉得错误结果为空不需要处理 直接返回空就好了
			return nil, nil
		}
		return nil, err
	}
	var names []string
	for rows.Next() {
		var name string

		err := rows.Scan(&name)
		if err != nil {
			return nil, errors.Wrap(err, "导出值错误")
		}
		names = append(names, name)
	}
	return names, nil
}

func main() {
	user := "root"
	pass := "root"
	host := "127.0.0.1"
	port := "3306"
	dbname := "test"

	dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/%s", user, pass, "tcp", host, port, dbname)
	var err error
	DB, err = sql.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("Open mysql failed,err:%v\n", err)
		fmt.Printf("%+v", err)
		os.Exit(1)
	}
	DB.SetConnMaxLifetime(100 * time.Second) //最大连接周期，超过时间的连接就close
	DB.SetMaxOpenConns(100)                  //设置最大连接数
	DB.SetMaxIdleConns(16)                   //设置闲置连接数

	names, err := getNames()
	if err != nil {
		fmt.Printf("获取结果失败:%v\n", err)
		fmt.Printf("%+v", err)
	}
	fmt.Println(names)
}
